package com.huaxin.hxcloud.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.HxFacilityTaskDetailBean;
import com.huaxin.common.Entity.HxInHousePollingBean;
import com.huaxin.common.Global;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by songxf on 2017/9/5.
 * 构筑物下巡检项和设备集合
 */

public class HxFacilityTaskDetailActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.tv_title)
    TextView     mTvTitle;
    @BindView(R.id.tv_station_name)
    TextView     mTvStationName;
    @BindView(R.id.more)
    TextView     mMore;
    @BindView(R.id.toolbar)
    Toolbar      mToolbar;
    @BindView(R.id.check_list)
    RecyclerView mBuildingRecyclerView;
    //    @BindView(R.id.divces_recyclerview)
    //    RecyclerView mDivcesRecyclerView;
    @BindView(R.id.content)
    FrameLayout  mContent;

    private int    mXjStructureId;
    private String mStructreName;
    private String mStaticonName;
    private int    mIsFinish;
    private int    mLayoutPostion;
    //构筑物adpater 集合
    private List<HxFacilityTaskDetailBean.DataBean.StructureListBean> mBuildingDataBeen = new ArrayList<>();
    private HxBuildingTaskDetailAdapter mBuildingTaskAdapter;
    //设备 workTaskListAdapter 集合
    private List<HxFacilityTaskDetailBean.DataBean.DeviceJaListBean> mDeviceDataBeanList = new ArrayList<>();
    private HxDeviceTaskDetailAdater mDeviceTaskDetailAdater;

    public static void start(Activity context, HxInHousePollingBean.DataBean dataBean, int layoutPosition) {
        Intent intent = new Intent(context, HxFacilityTaskDetailActivity.class);
        intent.putExtra(Constants.IK_XJ_ID, dataBean.getXjStructureId());
        intent.putExtra(Constants.IK_XJ_BUILDING, dataBean.getStructureName());
        intent.putExtra(Constants.IK_XJ_STATION_NAME, dataBean.getStationName());
        intent.putExtra(Constants.IK_XJ_STATE, dataBean.getIsFinish());
        intent.putExtra(Constants.IK_XJ_POSITION, layoutPosition);
        context.startActivityForResult(intent, Constants.RET_XJ_STATE);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_XJ_ID)) {
            mXjStructureId = extras.getInt(Constants.IK_XJ_ID);
            mStructreName = extras.getString(Constants.IK_XJ_BUILDING);
            mStaticonName = extras.getString(Constants.IK_XJ_STATION_NAME);
            mIsFinish = extras.getInt(Constants.IK_XJ_STATE);
            mLayoutPostion = extras.getInt(Constants.IK_XJ_POSITION);
        } else {
            finish();
        }
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_facility_detail;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        setSupportActionBar(mToolbar);
        mToolbar.setTitle("巡检单");
        mMore.setText("提交");
        mMore.setVisibility(mIsFinish == 1 ? View.GONE : View.VISIBLE);
        //公司名字
        mTvTitle.setText(Global.user.getOrgName());
        //站点名称+构筑物名称
        mTvStationName.setText(mStaticonName+"："+mStructreName);
        //构筑物巡检Adpater
        mBuildingRecyclerView.setHasFixedSize(true);
        mBuildingRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mBuildingTaskAdapter = new HxBuildingTaskDetailAdapter(this, mIsFinish, mBuildingDataBeen);
        mBuildingRecyclerView.setAdapter(mBuildingTaskAdapter);

        //添加headView
        View headView = LayoutInflater.from(this).inflate(R.layout.item_facility_task_title, null, false);
        mBuildingTaskAdapter.setHeaderView(headView);

        //添加FooterView
        View footerView = LayoutInflater.from(this).inflate(R.layout.item_device_recyclerview, null, false);
        mBuildingTaskAdapter.setFooterView(footerView);
        RecyclerView mDivcesRecyclerView = (RecyclerView) footerView.findViewById(R.id.divces_recyclerview);

        //设备巡检Adpater
        mDivcesRecyclerView.setHasFixedSize(true);
        mDivcesRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDeviceTaskDetailAdater = new HxDeviceTaskDetailAdater(this, mIsFinish, mDeviceDataBeanList);
        mDivcesRecyclerView.setAdapter(mDeviceTaskDetailAdater);
        mMore.setOnClickListener(this);
    }

    @Override
    public void requestData() {
        ApiRequestData(LOADING);
    }

    private void ApiRequestData(int status) {
        updateLoadStatus(status);
        Call<HxFacilityTaskDetailBean> call = HxTransmitRequestHelper.getRequestApi().getFindXjStructuenInfo(mXjStructureId);
        autoClose(call);
        call.enqueue(new Callback<HxFacilityTaskDetailBean>() {


            @Override
            public void onResponse(Call<HxFacilityTaskDetailBean> call, Response<HxFacilityTaskDetailBean> response) {
                HxFacilityTaskDetailBean taskDetailBean = response.body();
                if (response.isSuccessful() && taskDetailBean.isSuccessful()) {
                    updateLoadStatus(LOAD_SUCCESS);
                }
                if (taskDetailBean.getData().getStructureList().size() == 0 && taskDetailBean.getData().getDeviceJaList().size() == 0) {
                    updateLoadStatus(LOAD_NO_DATA);
                    return;
                }


                taskDetailBean.getData().getDeviceJaList();

                mBuildingTaskAdapter.setNewData(taskDetailBean.getData().getStructureList());

                mDeviceDataBeanList.addAll(taskDetailBean.getData().getDeviceJaList());
                mDeviceTaskDetailAdater.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<HxFacilityTaskDetailBean> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });

    }

    //提交巡检单

    @Override
    public void onClick(View view) {
        /*xunJianStructureId  巡检构筑物id
       xunJianItemData  所有巡检项id和状态
       JSONArray ：id，checkState*/
        List<HxFacilityTaskDetailBean.DataBean.StructureListBean> structureListBeens = mBuildingTaskAdapter.getData();
        List<HxFacilityTaskDetailBean.DataBean.DeviceJaListBean> deviceJaListBeens = mDeviceTaskDetailAdater.getData();
        JSONArray jsonArray = new JSONArray();
        try {
            for (HxFacilityTaskDetailBean.DataBean.StructureListBean structureListBeen : structureListBeens) {
                JSONObject object = new JSONObject();
                object.put("idNum", structureListBeen.getIdNum());
                object.put("checkState", structureListBeen.getCheckState());
                jsonArray.put(object);
            }

            for (HxFacilityTaskDetailBean.DataBean.DeviceJaListBean deviceJaListBeen : deviceJaListBeens) {
                for (HxFacilityTaskDetailBean.DataBean.DeviceJaListBean.DeviceItemBean deviceItem : deviceJaListBeen.getDeviceItem()) {
                    JSONObject object = new JSONObject();
                    object.put("idNum", deviceItem.getIdNum());
                    object.put("checkState", deviceItem.getCheckState());
                    jsonArray.put(object);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String flagData = jsonArray.toString();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().putCommitXunJianStructue(mXjStructureId, flagData);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                ToastUtil.showToast(response.body().getMsg());
                if (response.body().isSuccessful()) {
                    Intent intent = new Intent();
                    intent.putExtra(Constants.IK_XJ_POSITION, mLayoutPostion);
                    intent.putExtra(Constants.IK_XJ_STATE, 1);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast(R.string.network_faile);
            }
        });
    }


}
